package com.business.api;

import java.util.Set;

import javax.annotation.Resource;

import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.xserver.common.util.DateUtil;
import org.xserver.common.util.MessageUtils;
import org.xserver.common.util.StringUtil;
import org.xserver.component.annotation.WebSocketResolver;
import org.xserver.component.core.websocket.KeepAliveWebsocketResolver;
import org.xserver.component.core.websocket.WSMessage;
import org.xserver.component.core.websocket.WebSocketCacheManager;
import org.xserver.component.core.websocket.WebSocketClient;
import org.xserver.component.json.JsonManager;
import org.xserver.component.redis.RedisTemplate;
import org.xserver.component.redis.util.RedisConstant;

import redis.clients.jedis.Tuple;

import com.business.bean.DefaultJsonResponse;
import com.business.bean.TokenInfo;
import com.business.bean.UserInfo;
import com.business.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * //此处websocket接口 类注释指代topic 方法注释指代contentType
 * @author Idol
 *
 * @param <T>
 */
@Component
@WebSocketResolver("websocket1")
public class DefaultWebsocketResolver<T extends WebSocketFrame> extends KeepAliveWebsocketResolver<WebSocketFrame> {

	public static final Logger logger = LoggerFactory
			.getLogger(DefaultWebsocketResolver.class);
@Resource
private WebSocketCacheManager cacheManager;
	@Resource
	RedisTemplate redisTemplate;
	@Resource
	private UserService userService;

	@WebSocketResolver("login")
	public void login(WSMessage message, String id) {
		DefaultJsonResponse<Object> response = new DefaultJsonResponse<Object>();
		try {
			logger.info(message.getContent());
			UserInfo user = JsonManager.getBean(message.getContent(), UserInfo.class);
			if(user==null){
				response.setCode(Constant.INVALID_PARAMA_ERROR+"");
				response.setMsg(Constant.INVALID_PARAMA_ERROR_MSG);
			}
			if(StringUtil.isEmpty(user.getUserId())||StringUtil.isEmpty(user.getPassword())){
				response.setCode(Constant.INVALID_PARAMA_ERROR+"");
				response.setMsg(Constant.INVALID_PARAMA_ERROR_MSG);
			}
			response.setCode(Constant.SUCCESS_CODE+"");
			response.setMsg(Constant.SUCCESS_CODE_MSG);
			response.setResult(new TokenInfo(userService.getAccessToken(user.getUserId())));
			
			WebSocketClient client = cacheManager.getWebSocketClient(id);
			MessageUtils.sendMessage(client ,JsonManager.json(response));
		} catch (Exception e) {
			logger.error("",e);
		} 
	}
	@WebSocketResolver("onUnSubscribe")
	public void onUnSubscribe(WSMessage message, String id) {
		DefaultJsonResponse<Object> response = new DefaultJsonResponse<Object>();
		try {
			logger.info(message.getContent());
			response.setCode(Constant.SUCCESS_CODE+"");
			response.setMsg("这是一条推送消息");
			WebSocketClient client = cacheManager.getWebSocketClient(id);
			MessageUtils.sendMessage(client , JsonManager.json(response));
		} catch (Exception e) {
			logger.error("",e);
		}
	}
	@WebSocketResolver("onSubscribe")
	public void onSubscribe(WSMessage message, String id) {
		DefaultJsonResponse<Object> response = new DefaultJsonResponse<Object>();
		try {
			logger.info(message.getContent());
			response.setCode(Constant.SUCCESS_CODE+"");
			response.setMsg("这是一条推送消息2");
			WebSocketClient client = cacheManager.getWebSocketClient(id);
			MessageUtils.sendMessage(client , JsonManager.json(response));
		} catch (Exception e) {
			logger.error("",e);
		}
		
	}
	@WebSocketResolver("subscribeClient")
	public void subscribeClient(WSMessage message, String id) {
		
	}
	//此处websocket接口 类注释指代topic 方法注释指代contentType
	@WebSocketResolver("tradeBuy")
	public void tradeBuy2(WSMessage message, String id) {
		try {
			logger.info(message.getPrice());
			String timeString = DateUtil.now(DateUtil.DF_yyyy_MM_dd_HHmmss);
			//long end  = DateUtil.get
			//WebSocketClient client = cacheManager.getWebSocketClient(id);
			//MessageUtils.sendMessage(client , message.getPrice());
			//redisTemplate.listRange(RedisConstant.TRANDE_INFO_SELL+message.getPrice(), start, end);
			String priceString = message.getPrice();
			double score = 0;
			Set<Tuple> tuples = redisTemplate.ZRANGEBYSCORE(priceString);
			 double prices =  Double.valueOf(priceString);
			 double temp = 0;
			 String key = "";
			 for (Tuple tuple : tuples) {
				 logger.info(tuple.getElement() + ":" + tuple.getScore());
				 double a = Math.abs(tuple.getScore()-prices);
				  if(temp>0){
					  temp =a;
				  }else{
					  key = tuple.getElement();
					  score = tuple.getScore();
				  }
				 
		     }
			/*Set<String> sets= redisTemplate.keys(RedisConstant.TRANDE_INFO_SELL+message.getPrice());
			for (String str : sets) {  
				logger.info(str);
			}  */
			String sellerString = redisTemplate.getValue(key);
			logger.info("卖家信息为："+sellerString);
			if(StringUtil.isEmpty(sellerString)){
				message.setTime(timeString);
				String json = JsonManager.json(message);
				redisTemplate.setKeyValueExpire(RedisConstant.TRANDE_INFO_BUY+message.getPrice()+timeString, json, RedisConstant.accessTokenTimeout);
				redisTemplate.ZREMRANGEBYSCORE(score+"");
			}else{
				//得到卖家信息 进行交易逻辑
				WSMessage sellerMessage = JsonManager.getBean(sellerString, WSMessage.class);
				logger.info("交易成功");
				WebSocketClient client = cacheManager.getWebSocketClient(id);
				MessageUtils.sendMessage(client , "交易成功");
				//次数删除时 如果有重复的怎么办？
				redisTemplate.ZREMRANGEBYSCORE(sellerMessage.getPrice());
			}
			
		} catch (Exception e) {
			logger.error("",e);
		}
	}
	
	@WebSocketResolver("tradeSell")
	public void tradeSell2(WSMessage message, String id) {
		try {
			logger.info(message.getPrice());
			String timeString = DateUtil.now(DateUtil.DF_yyyy_MM_dd_HHmmss);
			String key = RedisConstant.TRANDE_INFO_SELL+message.getPrice()+timeString;
			//WebSocketClient client = cacheManager.getWebSocketClient(id);
			//MessageUtils.sendMessage(client , message.getPrice());
			message.setTime(timeString);
			String json = JsonManager.json(message);
			//此处list的范围可取小一点，我取得是整数，可将list存储时的keys 设定在小数后一位
			//SortedSetTypeTest 中有其他用法 可将其范围内取出 ，避免取出过大的数组 交易完成后，需将卖家相关的信息移除
			redisTemplate.ZADD(key,message.getPrice());
			redisTemplate.setKeyValueExpire(key, json, RedisConstant.accessTokenTimeout);
			
			
		} catch (Exception e) {
			logger.error("",e);
		}
	}
	
	public String dealPrice(String price){
		int legth = price.length();
		
		
		return null;
	}
	
	

}
